package com.jin.webvideo.controller;

import com.alibaba.fastjson.JSONObject;
import com.jin.webvideo.base.LoginHandler;
import com.jin.webvideo.externalInterfaces.PlatformSupport;
import com.jin.webvideo.externalInterfaces.entity.Filmography;
import com.jin.webvideo.entity.ResultEntity;
import com.jin.webvideo.service.ApiService;
import com.jin.webvideo.service.ShareRoomService;
import com.jin.webvideo.service.VideoService;
import com.jin.webvideo.util.sys.*;
import com.jin.webvideo.websocket.shareroom.ShareRoom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/share")
public class ShareController {
    @Autowired
    private ShareRoomService shareRoomService;
    @Autowired
    private ApiService apiService;
    @Autowired
    private VideoService videoService;

    /**
     * 是否支持共享室功能
     * @param session
     * @param docid
     * @param tvid
     * @param platform
     * @return
     */
    @ResponseBody
    @PostMapping("/support")
    public ResultEntity supportShareRoom(HttpSession session, String docid, String tvid, String platform){
        String account = LoginHandler.getAccount(session);
        if (null == account){
            return ResultEntity.fail("该功能仅对登录用户开放");
        }
        if (!shareRoomService.supportShareRoom(docid, tvid, platform)){
            return ResultEntity.fail("该视频不支持放映室功能");
        }
        return ResultEntity.success();
    }

    /**
     * 播放室页面
     * @param request
     * @param session
     * @param key
     * @return
     */
    @GetMapping("/room")
    public String room(HttpServletRequest request, HttpSession session, long key) {
        String account = LoginHandler.getAccount(session);
        // 返回ws地址
        ResultEntity rst = wsAddr(request, key, account);
        request.setAttribute("result", JSONObject.toJSONString(rst));
        return "shareRoom#c";
    }

    @GetMapping("/sharePlay")
    public String play(HttpServletRequest request, String platform, String docid, String tvid, @RequestParam(required = false) String url, @RequestParam(required = false) String data, @RequestParam(required = false, defaultValue = "false") boolean isphone) throws Exception {
        Filmography filmography = null;
        if (PlatformSupport.isSupport(platform)){
            filmography = apiService.getActiveVideoInformation(platform, docid, tvid);
            videoService.addVideoInfo(filmography);
        }
        request.setAttribute("info", filmography);
        return "sharePlay#p";
    }

    @ResponseBody
    @GetMapping("/createRoom")
    public ResultEntity createRoom(HttpServletRequest request, HttpSession session){
        String account = LoginHandler.getAccount(session);
        long roomid = shareRoomService.createRoom(account);
        ResultEntity rst = wsAddr(request, roomid, account);
        if (rst.getCode() == ResultEntity.CODE_FAIL){
            return rst;
        }
        Map<String,Object> result = new HashMap<>();
        result.put("roomAddr", rst.getData());
        result.put("key", roomid);
        return ResultEntity.success(result);
    }
    @ResponseBody
    @GetMapping("/listRoomInfos")
    public List<ShareRoom> list(){
        return shareRoomService.listRoomInfo();
    }
    @ResponseBody
    @GetMapping("/closeRoom")
    public String closeRoom(long roomId){
        shareRoomService.closeRoom(roomId);
        return "success";
    }
    private ResultEntity token(long roomId, String account) {
        if (null == account){
            return ResultEntity.fail("未登录，该功能仅对已登录用户开放");
        }
        ShareRoom room = shareRoomService.findByRoomId(roomId);
        if (null == room){
            return ResultEntity.fail("该房间已关闭或不存在");
        }
        return ResultEntity.success((Object) shareRoomService.createToken(account, String.valueOf(roomId)));
    }
    private ResultEntity wsAddr(HttpServletRequest request, long key, String account){
        String host = request.getServerName()+":"+request.getServerPort();
        String template = "ws://%s/api/shareroom/%d?token=%s";
        long roomRandom = EncryptUtil.random(100000, 1000000000);
        ResultEntity rst = token(key, account);
        if (rst.getCode() == ResultEntity.CODE_SECCESS){
            String addr = String.format(template, host, roomRandom, (String)rst.getData());
            rst = ResultEntity.success((Object) addr);
        }
        return rst;
    }
}
